import {
  addPlatFormUser,
  deletePlatFormUser,
  editPlatFormUser,
  selectAllPlatFormRole,
  mSelectPlatFormUserByPage
} from '@/api/conf'
import { FormInstance } from 'ant-design-vue'
import { PropType } from 'vue'
import './components.less'
import { CoustomTableFn } from '@/components/table'

/** 状态数据 */
interface Conf_administrator_state {
  /**角色列表 */
  role_list: SysDict.Item[]
  /**弹窗 */
  modal: {
    /**弹窗 关闭*/
    visible: boolean
    /**弹窗 类型*/
    type: string
    /**弹窗 标题*/
    title: string
    /**  弹窗 修改 数据源 */
    edit_source: {
      platFormUserDesc: string
      platFormUserId: string
      platFormUserName: string
      roleCode: string
    }
    add_source: {
      platFormUserDesc: string
      platFormUserName: string
      platFormUserPass: string
      roleCode: string
    }
  }
  table: CTable
  search: {
    platFormUserName: string
    roleCode: RoleCode
  }
}
let conf_administrator_state = reactive<Conf_administrator_state>({
  role_list: [],
  modal: {
    visible: false,
    type: '',
    title: '',
    edit_source: {
      platFormUserDesc: '',
      platFormUserId: '',
      platFormUserName: '',
      roleCode: ''
    },
    add_source: {
      platFormUserDesc: '',
      platFormUserName: '',
      platFormUserPass: '',
      roleCode: ''
    }
  },
  table: {
    dataSource: [],
    loading: false,
    pagination: {
      page: 1,
      size: 20
    },
    onPaginatiChange({ page, size }) {},
    total: 0
  },
  search: {
    platFormUserName: '',
    roleCode: ''
  }
})

/**获取表格数据 */
export async function getTableDatas(data?: any) {
  let { dataSource, pagination, total: tableTotal } = toRefs(conf_administrator_state.table)
  let { search } = toRefs(conf_administrator_state)
  let defaultData = {
    page: 1,
    size: 20,
    platFormUserName: '',
    roleCode: ''
  }
  Object.assign(defaultData, data, pagination.value, search.value)
  let res = await mSelectPlatFormUserByPage(defaultData).catch(err => {})
  if (!res) return
  let { list, total } = res.data
  dataSource.value = list
  tableTotal.value = total
}

const getAllRole = async () => {
  let { role_list } = toRefs(conf_administrator_state)
  let res = await selectAllPlatFormRole().catch(err => {})
  if (res) {
    role_list.value = res.data
  }
}

const handle_search_reset = () => {
  let { search } = toRefs(conf_administrator_state)
  Object.keys(search.value).forEach(key => {
    search.value[key as keyof typeof search.value] = ''
  })
  getTableDatas()
}
/** 左侧搜索区域 筛选区域 */
export const MainViewLeftFilter = defineComponent({
  name: 'ViewLeftFilter',
  setup() {
    let { search, role_list } = toRefs(conf_administrator_state)
    onMounted(() => {
      getAllRole()
    })
    function handle_sysdictType_checked(roleCode: RoleCode) {
      search.value.roleCode = roleCode || ''
      getTableDatas()
    }
    return () => (
      <div class='h-full viewLeftFilter'>
        <label for='viewLeftFilter'>
          <input
            type='radio'
            name='viewLeftFilter'
            id='viewLeftFilter'
            checked={search.value.roleCode === ''}
            class='hidden input_acitve'
          ></input>
          <div
            class='viewLeftFilter-line flex justify-between items-center text-sm truncate cursor-pointer py-2 hover:bg-primary_light'
            onClick={() => handle_sysdictType_checked('')}
          >
            <div class='viewLeftFilter-icon w-1/12'>
              <i class='iconfont'></i>
            </div>
            <div class='viewLeftFilter-label w-5/12'>全部</div>
            <div class='viewLeftFilter-value w-5/12  text-right pr-1 text-info text-xs'>
              查询所有类型
            </div>
          </div>
        </label>
        {role_list.value.map((type, idx) => (
          <label for={'viewLeftFilter' + idx}>
            <input
              type='radio'
              name='viewLeftFilter'
              id={'viewLeftFilter' + idx}
              checked={search.value.roleCode === type.dictCode}
              class='hidden input_acitve'
            ></input>
            <div
              class='viewLeftFilter-line flex justify-between items-center text-sm truncate cursor-pointer py-2 hover:bg-primary_light'
              onClick={() => handle_sysdictType_checked(type.dictCode)}
            >
              <div class='viewLeftFilter-icon w-1/12'>
                <i class='iconfont'></i>
              </div>
              <div class='viewLeftFilter-label w-5/12'>{type.dictName}</div>
              <div class='viewLeftFilter-value w-5/12  text-right pr-1 text-info text-xs'>
                {type.dictDesc}
              </div>
            </div>
          </label>
        ))}
      </div>
    )
  }
})

/** 左侧搜索区域 底部*/
export const MainViewLeftFooter = defineComponent({
  name: 'MainViewLeftFooter',
  setup() {
    return () => (
      <div class='w-full h-full flex justify-end items-center '>
        <a-button type='primary' class='mx-2' onClick={handle_search_reset}>
          重置
        </a-button>
        <a-button type='primary' class='mx-2' onClick={getTableDatas}>
          查询
        </a-button>
      </div>
    )
  }
})
/** 左侧搜索区域 头部*/
export const MainViewLeftNav = defineComponent({
  name: 'MainViewLeftNav',
  setup() {
    let { platFormUserName } = toRefs(conf_administrator_state.search)
    return () => (
      <div class='w-full h-full'>
        <a-input
          class='w-full h-full'
          placeholder='输入账号名,回车进行过滤'
          v-model={[platFormUserName.value, 'value']}
          onPressEnter={getTableDatas}
          allow-clear={true}
        ></a-input>
      </div>
    )
  }
})

/** 数据表格 头部 操作栏 */
export const MainViewNav = defineComponent({
  setup() {
    let { visible, title, type } = toRefs(conf_administrator_state.modal)
    const handle_add_btn_click = () => {
      visible.value = true
      type.value = 'addAdministrator'
      title.value = '添加管理员'
    }
    return () => (
      <div class='h-mainViewNav border-b border-default bg-white px-4 flex justify-start items-center'>
        <a-button type='primary' onClick={handle_add_btn_click}>
          添加
        </a-button>
      </div>
    )
  }
})

/**数据表格 操作栏 */
export const TypeHandleBtn = defineComponent({
  props: {
    record: {
      type: Object as PropType<User.PlatForm>,
      default: {}
    }
  },
  setup(props) {
    let { visible, title, type, edit_source } = toRefs(conf_administrator_state.modal)
    const handle_type_edit_btn_click = () => {
      visible.value = true
      type.value = 'editAdministrator'
      title.value = '修改管理员信息'
      Object.keys(edit_source.value).forEach(key => {
        let value = props.record[key as keyof User.PlatForm]
        edit_source.value[key as keyof typeof edit_source.value] =
          value !== undefined ? value.toString() : ''
      })
    }

    const handle_delete_click = () => {
      deletePlatFormUser({
        platFormUserId: props.record.platFormUserId
      })
        .then(res => {
          getTableDatas()
        })
        .catch(err => {})
    }
    return () => (
      <div>
        <span
          class='mr-2 text-primary border-b cursor-pointer'
          onClick={handle_type_edit_btn_click}
        >
          编辑
        </span>
        <a-popconfirm
          title={`确认删除管理员: ${props.record.platFormUserName} 吗?`}
          placement='topRight'
          ok-text='确认'
          cancel-text='取消'
          onConfirm={handle_delete_click}
          onCancel={() => {}}
        >
          <span class='mr-2 text-primary border-b cursor-pointer'>删除</span>
        </a-popconfirm>
      </div>
    )
  }
})

/** 数据表格 */
const CoustomTable = CoustomTableFn<User.PlatForm>()
export const MainViewContentTable = defineComponent({
  name: 'MainViewContent',
  setup(props) {
    let { dataSource, loading, total, onPaginatiChange } = toRefs(conf_administrator_state.table)
    let { page, size } = toRefs(conf_administrator_state.table.pagination)

    let columns: CColumn<any>[] = [
      {
        title: '账号名',
        dataIndex: 'platFormUserName',
        ellipsis: true
      },
      {
        title: '备注',
        dataIndex: 'platFormUserDesc',
        ellipsis: true
      },
      {
        title: '最后登录时间',
        dataIndex: 'lastLoginTime',
        ellipsis: true
      },
      {
        title: '所属角色',
        dataIndex: 'roleName',
        ellipsis: true
      },
      {
        title: '操作',
        dataIndex: 'util',
        isUtil: true,
        width: 140
      }
    ]

    return () => (
      <CoustomTable
        dataSource={dataSource.value}
        loading={loading.value}
        rowKey='platFormUserId'
        columns={columns}
        pagination={{
          page: page.value,
          size: size.value,
          total: total.value
        }}
        onPaginationChange={data => onPaginatiChange.value(data)}
      >
        {{
          util: (record: User.PlatForm) => <TypeHandleBtn record={record}></TypeHandleBtn>
        }}
      </CoustomTable>
    )
  }
})

/**弹窗 表单 添加用 */
const AddFormOfModal = defineComponent({
  name: 'AddFormOfModal_role',
  emits: ['finish'],
  setup(props, { emit }) {
    let formRef = ref<FormInstance>()
    let { add_source } = toRefs(conf_administrator_state.modal)
    let { role_list } = toRefs(conf_administrator_state)
    let onLoading = ref(false)
    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      // console.log(add_source.value)
      onLoading.value = true
      await addPlatFormUser(add_source.value).catch(err => {})
      setTimeout(() => {
        returnEmit()
      }, 300)
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed', add_source.value)
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      returnEmit()
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      onLoading.value = false
      formRef.value?.resetFields()
      emit('finish')
    }

    return () => (
      <a-form
        v-model={[formRef, 'ref']}
        name='addAuth'
        model={add_source.value}
        label-col={{ span: 4 }}
        wrapper-col={{ span: 16 }}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        <a-form-item label='账号' name='platFormUserName'>
          <a-input v-model={[add_source.value.platFormUserName, 'value']} />
        </a-form-item>
        <a-form-item label='密码' name='authMethod'>
          <a-input v-model={[add_source.value.platFormUserPass, 'value']} />
        </a-form-item>
        <a-form-item label='角色' name='roleCode'>
          <a-select
            v-model={[add_source.value.roleCode, 'value']}
            options={role_list.value}
            fieldNames={{
              label: 'dictName',
              value: 'dictCode'
            }}
          ></a-select>
        </a-form-item>
        <a-form-item label='备注' name='authDesc'>
          <a-input v-model={[add_source.value.platFormUserDesc, 'value']} />
        </a-form-item>
        <a-form-item>
          <a-button
            type='primary'
            class='float-right mx-4'
            html-type='submit'
            loading={onLoading.value}
          >
            提交
          </a-button>
          <a-button class='float-right mx-4' onClick={handle_form_cancel}>
            取消
          </a-button>
        </a-form-item>
      </a-form>
    )
  }
})

/**弹窗 表单 修改用 */
const EditFormOfModal = defineComponent({
  name: 'EditFormOfModal_role',
  emits: ['finish'],
  setup(props, { emit }) {
    let { role_list } = toRefs(conf_administrator_state)
    let { edit_source } = toRefs(conf_administrator_state.modal)
    let formRef = ref<FormInstance>()

    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      await editPlatFormUser(edit_source.value).catch(err => {})
      setTimeout(() => {
        returnEmit()
      }, 300)
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed', edit_source.value)
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      returnEmit()
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      formRef.value?.resetFields()
      emit('finish')
    }
    return () => (
      <a-form
        v-model={[formRef, 'ref']}
        name='editSysdictType'
        model={edit_source.value}
        label-col={{ span: 4 }}
        wrapper-col={{ span: 16 }}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        <a-form-item label='账号' name='platFormUserName'>
          <a-input v-model={[edit_source.value.platFormUserName, 'value']} />
        </a-form-item>
        <a-form-item label='备注' name='platFormUserDesc'>
          <a-input v-model={[edit_source.value.platFormUserDesc, 'value']} />
        </a-form-item>
        <a-form-item label='角色' name='roleCode'>
          <a-select
            v-model={[edit_source.value.roleCode, 'value']}
            options={role_list.value}
            fieldNames={{
              label: 'dictName',
              value: 'dictCode'
            }}
          ></a-select>
        </a-form-item>
        <a-form-item>
          <a-button type='primary' class='float-right mx-4' html-type='submit'>
            提交
          </a-button>
          <a-button class='float-right mx-4' onClick={handle_form_cancel}>
            取消
          </a-button>
        </a-form-item>
      </a-form>
    )
  }
})

/** 弹窗 */
export const MainViewModel = defineComponent({
  setup(props, { emit }) {
    let { visible, type, title } = toRefs(conf_administrator_state.modal)
    const handle_form_finish = () => {
      visible.value = false
      type.value = ''
      title.value = ''
      getTableDatas()
    }
    return () => {
      let dynamicCom
      switch (type.value) {
        case 'addAdministrator':
          dynamicCom = <AddFormOfModal onFinish={handle_form_finish}></AddFormOfModal>
          break
        case 'editAdministrator':
          dynamicCom = <EditFormOfModal onFinish={handle_form_finish}></EditFormOfModal>
          break
      }
      return (
        <a-modal
          visible={visible.value}
          title={title.value}
          footer={null}
          onCancel={() => {
            handle_form_finish()
          }}
        >
          {dynamicCom}
        </a-modal>
      )
    }
  }
})
